package org.example.Thread.B_Thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @className: CallableDemo
 * @author: 芃
 * @description: Callable接口测试
 * @date: 2024/5/13 11:26
 */
/*
 * Callable的好处
 * 1. 可以返回值，
 * 2. 可以抛出异常
 */
public class CallableDemo implements Callable<Boolean> {

    private String url;
    private String fileName;

    public CallableDemo(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    @Override
    public Boolean call() throws Exception {
        WebDownloader downloader = new WebDownloader();
        downloader.download(url, fileName);
        System.out.println("下载完成" + fileName);
        return true;
    }

    public static void main(String[] args) {
        CallableDemo downloadThread1 = new CallableDemo("https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2905957300.webp","星球崛起4.jpg");
        CallableDemo downloadThread2 = new CallableDemo("https://pics3.baidu.com/feed/b7fd5266d0160924dbe42d537dab3ef7e4cd34ea.jpeg@f_auto?token=ddd95518a2d7f01c1bab545c44745364","复仇者联盟5.jpg");
        CallableDemo downloadThread3 = new CallableDemo("https://pics2.baidu.com/feed/960a304e251f95ca5d2ae4a772155132660952d6.jpeg@f_auto?token=1d63bfa314d680c80e72ac882cde27dd","阿凡达3.jpg");
        //创建执行服务
        ExecutorService executor = Executors.newFixedThreadPool(3);
        //提交执行任务
        Future<Boolean> future1 = executor.submit(downloadThread1);
        Future<Boolean> future2 = executor.submit(downloadThread2);
        Future<Boolean> future3 = executor.submit(downloadThread3);
        //获取执行结果
        try {
            Boolean result1 = future1.get();
            Boolean result2 = future2.get();
            Boolean result3 = future3.get();
            System.out.println("下载完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //关闭执行服务
        executor.shutdown();
    }
}
